<?php

namespace App\Services\Reward;

use Carbon\Carbon;
use App\Models\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;

class RewardDivider
{

	protected function setUser(User $user)
	{
		$this->user = $user;
	}

	protected function getSelfReward()
	{	


		if(Carbon::today()->day  >= 1 && Carbon::today()->day < 11){

			$searchStartTime = Carbon::today()->subMonth()->day(11);
			$searchEndTime = Carbon::today()->subMonth()->day(21);
		}elseif(Carbon::today()->day  >= 11 && Carbon::today()->day < 21){

			$searchStartTime = Carbon::today()->subMonth()->day(21);
			$searchEndTime = Carbon::today()->day(1);

		}else{
			$searchStartTime = Carbon::today()->day(1);
			$searchEndTime = Carbon::today()->day(11);

		}
		return $this->user->rewards()
			->where(function (Builder $query) {
				 $query->where('remark','own_order')->orWhere('remark', 'first_level')->orWhere('remark', 'second_level')->orWhere('remark', 'rewards_refund')->orWhere('remark', 'rewards_refund_first')->orWhere('remark', 'rewards_refund_second');
			})
			->where('is_settle',false)
			->where('created_at', '>=', $searchStartTime)
			->where('created_at', '<=', $searchEndTime);
	}

	public function divide()
	{


		
		//dd($searchStartTime);
		User::query()
			//->whereDate('created_at', '>=', $searchStartTime)
			//->whereDate('created_at', '<=', $searchEndTime)
			->chunkById(100, function (Collection $users) {
				if ($users->isEmpty()) return;
				
				foreach ($users as $user) {
					
					if ($user->rewards()->doesntExist()) continue;
					
				    $this->settle($user);
					Log::debug("User: {$user->id} settled.");
					
					usleep(100);
				}
				
			});
	}


	public function settle(User $user)
	{
		$this->setUser($user);
		
		DB::transaction(function () use($user){
			
			$selfBrokerage = $this->getSelfReward();
			$money = $selfBrokerage->sum('money');

			if($money >  0){

				$selfMoney = big_decimal($money);
				$selfBrokerage->update(['is_settle' => true]);
				
				
				account_rewards($user)->minusRewardsToBalances($selfMoney);
				account_balances($user)->plusRewardsToBalances($selfMoney);
			}

			
		});
	}
	
	public function run()
	{
		/*if (Carbon::today()->day !== 20) {
			return;
		}*/
		
		Log::info("reward settlement started.");
		
		$this->divide();
		
		Log::info("reward settlement ended.");
	}
}
